package Top200;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * @author zhangmin
 * @create 2022-02-18 10:52
 */
public class threeSum15 {
    public List<List<Integer>> twoSum(int[] nums,int start,int target){
        int left=start,right=nums.length-1;
        List<List<Integer>> res=new LinkedList<>();
        while (left<right){
            int sum=nums[left]+nums[right];
            int l=nums[left],r=nums[right];
            if (sum==target){
                List<Integer> list=new LinkedList<>();
                list.add(l);list.add(r);
                res.add(list);
                while (left<right&&nums[left]==l){
                    left++;
                }
                while (left<right&&nums[right]==r){
                    right--;
                }
            }else if (sum<target){
                while (left<right&&nums[left]==l){
                    left++;
                }
            }else {
                while (left<right&&nums[right]==r){
                    right--;
                }
            }
        }
        return res;
    }

    public List<List<Integer>> threeSum(int[] nums) {
        int n=nums.length;
        Arrays.sort(nums);
        List<List<Integer>> res=new LinkedList<>();
        if (n<=2) return res;
        for (int i = 0; i < n; i++) {
            List<List<Integer>> two = twoSum(nums, i +1, 0 - nums[i]);
            for (int j = 0; j < two.size(); j++) {
                List<Integer> list = two.get(j);
                list.add(nums[i]);
                res.add(list);
            }
            while (i+1<n&&nums[i]==nums[i+1])i++;
        }
        return res;
    }
}
